package com.lemon.dao;

import java.util.List;

import org.apache.ibatis.session.SqlSession;

import com.lemon.domain.Menu;
import com.lemon.util.MybatisUtils;

public class MenuDao {


	/**
	 * 查找菜单
	 * @param id
	 * @return
	 */
	public Menu get(Long id) {
		SqlSession session = MybatisUtils.getSession();
		Menu m;
		try {
			m = session.selectOne("com.lemon.mapper.MenuMapper.get", id);
		} finally {
			session.close();
		}

		return m;
	}
	
	/**
	 * 查询一个菜单的所有子菜单
	 * @param id
	 * @return
	 */
	public List<Menu> listSubmenu(Long id) {
		SqlSession session = MybatisUtils.getSession();
		List<Menu> list;
		
		try {
			if (id != null) {
				list = session.selectList("com.lemon.mapper.MenuMapper.listSubmenu", id);
			} else {
				list = session.selectList("com.lemon.mapper.MenuMapper.superiorMenuIdIsNull");
			}
		} finally {
			session.close();
		}

		return list;
	}
	
	/**
	 * 查找所有菜单
	 * @return
	 */
	public List<Menu> list() {
		SqlSession session = MybatisUtils.getSession();
		List<Menu> list;
		
		try {
			list = session.selectList("com.lemon.mapper.MenuMapper.list");
		} finally {
			session.close();
		}

		return list;
	}
	
	/**
	 * 插入
	 * @param m
	 * @return
	 */
	public Long save(Menu m) {
		SqlSession session = MybatisUtils.getSession();
		
		try {
			session.insert("com.lemon.mapper.MenuMapper.save", m);
			session.commit();
		} finally {
			session.close();
		}
		
		return m.getId();
	}
	
	/**
	 * 删除
	 * @param id
	 * @return
	 */
	public int delete(Long id) {
		SqlSession session = MybatisUtils.getSession();
		int rows;
		
		try {
			rows = session.delete("com.lemon.mapper.MenuMapper.delete", id);
			session.commit();
		} finally {
			session.close();
		}
		
		return rows;
	}
	
	/**
	 * 修改
	 * @param m
	 * @return
	 */
	public int update(Menu m) {
		SqlSession session = MybatisUtils.getSession();
		int rows;
		
		try {
			rows = session.update("com.lemon.mapper.MenuMapper.update", m);
			if (rows == 1) {// 如果没有记录被修改，那么该事物就不用提交了
				session.commit();
			} 
		} finally {
			session.close();
		}
		
		return rows;
	}
}
